/**
 * Created by kirno on 2017/4/14.
 */
/**
 * Created by Administrator on 2016/11/12.
 */
import {message} from 'antd'
import {config} from './config';
import reqwest from "reqwest";
import Promise from 'bluebird';

const path = config.path;
const app = {
    serverUrl: config.serverUrl,
    imgServerUrl: config.imgServerUrl,
    fileUrl: config.fileUrl,
    loadIndex: "",
    pageLength: 20,

    setToken: function (token) { //存储Token值
        return localStorage.setItem("shopToken", token);  //localStorage没有时间限制的数据存储。添加键值对：localStorage.setItem(key,value)，将value存储到key字段
    },
    getToken: function () {  //获取token值
        return localStorage.getItem("shopToken"); //　获取键值：localStorage.getItem(key)
    },
    removeToken() {
        localStorage.removeItem("shopToken");
    },
    /**
     *   存储值
     */
    setData: function (key, value) {
        if (!value) {
            return;
        }
        if (typeof value == 'object') {
            localStorage.setItem(key, JSON.stringify(value));
        } else {
            localStorage.setItem(key, value);
        }
    },
    /**
     * 获取存储的值
     * @key 需要的值对应的Key
     * @defaultData 当返回的值是空的时候，返回
     */
    getData(key, defaultData) {
        try {
            let re = localStorage.getItem(key);
            if (re) {
                return JSON.parse(re);
            } else {
                return defaultData;
            }
        } catch (e) {
            return e;
        }
    },
    removeDate(key) {
        localStorage.removeItem(key);
    },
    post: function (url, data) {
        // 以下两个固定传给服务器的参数
        //data.token = app.getToken();

        const re = app.ajax(url, data, "POST");
        return re;
    },
    postJson(url, data, succCallBack, errorCallBack) {
        data.token = this.getToken();
        data.log_type = '1';
        data.log_shop = app.getData('shop_id');
        data.shop_id = app.getData('shop_id');
        this.ajaxJson(url, JSON.stringify(data), "POST", succCallBack, errorCallBack, "application/json; charset=utf8");
    },
    ajaxJson(url, data, method, succCallBack, errorCallBack) {
        this.ajax(url, data, method, succCallBack, errorCallBack, "application/json; charset=utf8");
    },
    put: function (url, data, succCallBack, errorCallBack) {
        app.ajax(url, data, "PUT", succCallBack, errorCallBack);
    },
    get: function (url, data) {
        let reqParam = "";
        if (data) {
            for (let key in data) {
                const item = data[key];
                if (!item) {
                    continue;
                }
                reqParam += key + "=" + item + "&"
            }
            reqParam += "token=" + app.getToken();
        }
        return app.ajax(url + "?" + reqParam, {}, "GET");
    },
    del: function (url, data) {
        let reqParam = "";
        for (let key in data) {
            reqParam += key + "=" + data[key] + "&"
        }
        reqParam.substr(0, reqParam.length - 1);
        return app.ajax(url + "?" + reqParam, {}, "DELETE");
    },
    ajax: function (url, data, method, contentType = 'application/x-www-form-urlencoded; charset=utf8',) {
        const reqUrl = config.serverUrl + url;
        app.log(reqUrl);
        const token = this.getToken();
        return new Promise((resolve) => {
            reqwest({
                url: reqUrl,
                data: data,
                method: method,
                dataType: "json",
                timeout: 500000,
                contentType: contentType,
                headers: {'token': token}
            }).then((req) => {
                if(typeof req=='string'&&req.constructor==String){
                    req=JSON.parse(req);
                }
                const {code, msg, data} = req;
                if (code === 1) {
                    app.log("请求：" + reqUrl + " 返回的数据：" + JSON.stringify(data));
                } else {
                    app.error("请求：" + reqUrl + " 返回的数据：" + JSON.stringify(msg));
                }
                switch (code) {
                    // 掉线的情况
                    case -1:
                        app.removeToken();
                        app.removeDate('user_id');
                        app.alert('请重新登录', 'error', 3);
                        window._this.props.history.push(path + '/login')
                }
                resolve(req);
            }, ({Status, readyState}) => {
                if (config.debug) {
                    app.alert(`请求地址：${url} 请求参数：${JSON.stringify(data)} 请求状态： ${Status}，XMLHttpRequest对象的状态：${readyState}`, "error", 10);
                } else {
                    app.alert("网络错误，请检查网络", "error", 3);
                }
            })
        })

    },
    tokenInvalid(location) {
        app.alert("请重新登陆");
        location.push('/');
    },
    /**
     * 日期检测
     */
    testDate(value) {
        const reg = /([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))/;
        return reg.test(value);
    },
    log(msg) {
        if (config.debug) {
            console.log(msg);
        }
    },
    error(msg) {
        if (config.debug) {
            console.error(msg);
        }
    },
    /**
     * 弹出警告
     * @param msg 警告内容
     * @param times 时长 默认 1.5
     * @param type 警告类型可选值 success、error、warning、info 默认 info
     */
    alert(msg, type = "info", times = 1.5) {
        message.config({
            top: '35%',
            duration: 2,
        });
        message[type](msg, times);
    },
    /**
     * 返回n位的随机数
     * @param n
     * @returns {*}
     */
    getRandom(n) {
        let ran = Math.random() * Math.pow(10, n);
        ran += '';
        return ran[0]
    },
    maxCount(name, name2, data) {
        let value = 0;
        let value2 = 1;
        data.map((item) => {
            if (name2) {
                value2 = parseFloat(item[name2] || 0);
            }
            value += parseFloat(item[name] || 0) * value2 || 0
        });
        return name2 !== '' ? parseFloat(value).toFixed(2) : value;
    },
    /**
     *判断是否匹配
     */
    checkIsNull(data, type) {
        let name = '';
        data.map((item) => {
            if (type == item.key) {
                name = item.name;
            }
        });
        return name
    },
    getQueryString(name) {
        const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        const r = window.location.search.substr(1).match(reg);
        if (r !== null) return unescape(r[2]);
        return null;
    },
    compare(property) {
        return function (a, b) {
            let value1 = a[property];
            let value2 = b[property];
            if (value1 > value2) {
                return 1;
            } else if (value1 < value2) {
                return -1;
            } else {
                return 0;
            }
        }
    },
    compareTwo2(property) {
        return function (a, b) {
            let value1 = a[property];
            let value2 = b[property];
            if (value1 > value2) {
                return -1;
            } else if (value1 < value2) {
                return 1;
            } else {
                return 0;
            }
        }
    },
    // 键盘按下enter键，鼠标移到下一个输入框的焦点上，e表示事件，ID表示该标签的ID
    onKeyDown(e, id) {
        if (e.keyCode == '13') {
            document.getElementById(id).focus();
        }
    },

    // 回到顶部
    scrollTop() {
        window.scrollTo(0, 0);
    },

    // 去掉空格
    handleTrim(values) {
        let a = {};
        for (let i in values) {
            if (values[i]) {
                if (typeof values[i] === 'string') {
                    values[i] = values[i].trim();
                    a[i] = values[i].trim();
                    return a;
                }
            }
        }
    },

    /**
     * 去除前后空格
     */
    trim:function(str){
        str=str.replace(/\s+/g,"");
        return str;
    }
};

export default app;